import java.util.HashMap;
import java.util.Map;

/*
 * @lc app=leetcode.cn id=106 lang=java
 *
 * [106] 从中序与后序遍历序列构造二叉树
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    Map<Integer,Integer>map;//方便根据数查找位置
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        map=new HashMap<>();
        for(int i=0;i<inorder.length;i++){//map存放中序序列的数值对应位置
            map.put(inorder[i], i);
        }
        return dfs(inorder,0,inorder.length,postorder,0,postorder.length);
    }

    public TreeNode dfs(int[] inorder,int inBegin,int inEnd,int[] postorder,int postBegin,int postEnd){
        //采用前闭后开
        //如果数组长度为空，则分割完毕
        if(inBegin>=inEnd||postBegin>=postEnd){
            //不满足左闭右开，说明没有元素，返回空树
            return null;
        }
       //后序遍历数组的最后一个元素，就是当前的根节点
        int rootIndex=map.get(postorder[postEnd-1]);
        TreeNode root=new TreeNode(inorder[rootIndex]);//构造节点
        int lenOfLeft=rootIndex-inBegin;//保存中序左子树个数
        //递归处理左区间和右区间
        root.left=dfs(inorder, inBegin, rootIndex, 
                        postorder, postBegin,postBegin+lenOfLeft);
        root.right=dfs(inorder, rootIndex+1, inEnd, 
                        postorder, postBegin+lenOfLeft, postEnd-1);

        return root;
    }
}
// @lc code=end

